﻿/* Project: Side Scrolling Shooter
 * The bullet fired by enemies.
 * Can check  if it has collided with the player.
 * Last Update: 4/12/11,11:16PM
 */

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace TheFifthSpace
{
    public class EnemyBullet : DrawableGameComponent
    {
        public float posX, posY;

        //public bool IsAlive { get; set; }

        public Texture2D sprite;
        //private SpriteBatch spriteBatch;
        private Vector2 offset;
        private float dt;
        public Vector2 Velocity { get; set; }
        private float lifetime;
        public Vector2 Position
        {
            get
            {
                return new Vector2(posX, posY);
            }
            set
            {
                posX = value.X;
                posY = value.Y;
            }
        }

        // CONSTRUCTOR
        public EnemyBullet(Game g, Vector2 p, Vector2 v)
            : base(g)
        {
            Position = p;
            Velocity = v;
            Velocity = Vector2.Normalize(Velocity);
            Velocity *= 200f;
            Game.Components.Add(this);
            lifetime = 4;
        }

        public virtual void Die()
        {
            // Pre-death actions
            MainGame.EnemyBullets.Remove(this);
            Game.Components.Remove(this);
        }

        // LOAD CONTENT
        protected override void LoadContent()
        {
            sprite = MainGame.enemyBulletSprite;
            //spriteBatch = MainGame.spriteBatch;
            offset = new Vector2(sprite.Width / 2, sprite.Height / 2);
        }

        // DRAW
        public override void Draw(GameTime gameTime)
        {
            MainGame.spriteBatch.Begin();
            MainGame.spriteBatch.Draw(sprite, Position - offset, Color.White);
            MainGame.spriteBatch.End();
        }

        // Check to see if bullet has hit player
        public bool HitsPlayer(Rectangle pRect)
        {
            Rectangle myRect = new Rectangle(
                (int)(posX - offset.X), (int)(posY - offset.Y),
                sprite.Width, sprite.Height);
            if (myRect.Intersects(pRect)) return true;
            else return false;
        }

        public override void Update(GameTime gameTime)
        {
            dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
            this.Position += this.Velocity * dt;
            lifetime -= dt;

        }// END UPDATE
    }
}